package com.hcrazy.manchester.app.services;

import org.joda.time.DateTime;

import com.hcrazy.manchester.app.jdbc.SecondaryRequireDAO;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Secondary;
import com.hcrazy.manchester.app.pojo.SecondaryRequire;
import com.hcrazy.manchester.app.utils.Constant;

public class SecondaryRequireService {

	private SecondaryRequireDAO secondaryRequireDAO;

	public SecondaryRequireDAO getSecondaryRequireDAO() {
		return secondaryRequireDAO;
	}

	public void setSecondaryRequireDAO(SecondaryRequireDAO secondaryRequireDAO) {
		this.secondaryRequireDAO = secondaryRequireDAO;
	}

	public ErrorMsg addOrUpdateSecondaryRequire(SecondaryRequire SecondaryRequire) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		//设置发布时间
		DateTime date = new DateTime();
		
		//如果有效时间为空，则添加默认，默认为30天
		if(null == SecondaryRequire.getPublishValidateDate() || "".equals(SecondaryRequire.getPublishValidateDate())){
			DateTime validateDt = date.plusDays(30);
			SecondaryRequire.setPublishValidateDate(validateDt.toString("yyyy-MM-dd"));
		}
		
		if(SecondaryRequire.getInfoId()>0){
			SecondaryRequire.setUpdateDate(date.toString("yyyy-MM-dd hh:mm:ss"));
			secondaryRequireDAO.updateSecondaryRequire(SecondaryRequire);
		}else{
			SecondaryRequire.setPublishDate(date.toString("yyyy-MM-dd hh:mm:ss"));
			secondaryRequireDAO.addSecondaryRequire(SecondaryRequire);
		}
		
		return msg;
	}
	
	public PageModel getSecondaryInfos(PageModel model,String search,long userId) throws Exception{
		return secondaryRequireDAO.getPagedInfos(model, search,userId);
	}
	
	public PageModel getSecondaryInfos(PageModel model,String search,String username) throws Exception{
		return secondaryRequireDAO.getPagedInfos(model, search,username);
	}
	
	public SecondaryRequire getInfoById(long infoId) throws Exception{
		SecondaryRequire seconday = secondaryRequireDAO.getById(infoId);
		
		return seconday;
	}
	
	public void delSecondary(long infoId) throws Exception{
		secondaryRequireDAO.delSecondaryRequire(infoId);
	}
	
	public void delSecondary(long infoId,long userId) throws Exception{
		SecondaryRequire secondary = secondaryRequireDAO.getById(infoId);
		if(null != secondary && secondary.getUserId() > 0 && secondary.getUserId() == userId)
			secondaryRequireDAO.delSecondaryRequire(infoId);
	}
	
	public void setViews(long id) throws Exception{
		//获取对象
		SecondaryRequire SecondaryRequire = secondaryRequireDAO.getById(id);
		long views = SecondaryRequire.getViews()+1;
		//计数+1
		secondaryRequireDAO.setViews(views,id);
	}
}
